package com.jhgsys.internal.hazard.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.constant.ModuleManagerPermissionConstant;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.hazard.constant.HazardConstant;
import com.jhgsys.internal.hazard.dto.HazardReportDto;
import com.jhgsys.internal.hazard.entity.HazardReport;
import com.jhgsys.internal.hazard.service.IHazardReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author wanghw
 * @CreateTime 2024/8/21 15:59
 * @Description 隐患整改反馈
 * @Version 1.0
 */
@Slf4j
@Validated
@Controller
public class HazardReportRectificationController extends BaseController {
    @Autowired
    private IHazardReportService hazardReportService;



    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportRectification")
    @RequiresPermissions("hazardReportRectification:view")
    public String hazardReportRectificationIndex(Model model){
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("tenantList",getTenantList());
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportRectification/hazardReportRectificationList");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "hazardReportRectification/feedback/{id}")
    @RequiresPermissions("hazardReportRectification:feedback")
    public String hazardReportUpdate(Model model, @PathVariable("id") String id) throws JsonProcessingException {
        HazardReportDto dto = hazardReportService.findHazardReportById(id);
        model.addAttribute("hasHeadCompanyRole", hasHeadCompanyRole());
        model.addAttribute("hazardReport", JSON.parse(new ObjectMapper().writeValueAsString(dto)));
        model.addAttribute("currentTenantId", getCurrentTenantId());
        return FebsUtil.view("hazard/hazardReportRectification/hazardReportRectificationEdit");
    }

    /**
     * 制定计划查询（分页）
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @GetMapping("hazardReportRectification/list")
    @ResponseBody
    @RequiresPermissions("hazardReportRectification:view")
    public FebsResponse hazardReportList(QueryRequest request, HazardReportDto hazardReport) {
        List<String> statusList = Arrays.asList(HazardConstant.HAZARD_STATUS.RECTIFICATING,
                HazardConstant.HAZARD_STATUS.RECTIFICATION,
                HazardConstant.HAZARD_STATUS.BACK_AUDIT);
        hazardReport.setStatus(String.join(StringPool.COMMA, statusList));
        //如果不是总公司，或者模块管理员，只能看到分给自己的隐患信息
        if(!hasHeadCompanyRole() && !hasPermission(ModuleManagerPermissionConstant.HAZARD)){
            hazardReport.setLeaderId(getCurrentUserId());
        }
        Map<String, Object> dataTable = getDataTable(this.hazardReportService.findHazardReportPage(request, hazardReport));
        return new FebsResponse().success().data(dataTable);
    }

    /**
     * 整改反馈
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("新增整改反馈")
    @PostMapping("submitHazardReportRectification")
    @ResponseBody
    @RequiresPermissions("hazardReportRectification:feedback")
    public FebsResponse submitHazardReportRectification(@RequestBody  HazardReportDto hazardReport) throws FebsException {
        checkParams(hazardReport);
        try {
            HazardReport report = hazardReportService.findHazardReportById(hazardReport.getReportId());
            if(ObjectUtils.isEmpty(report)){
                return new FebsResponse().fail().message("待整改的隐患信息不存在!");
            }
            if (!HazardConstant.HAZARD_STATUS.RECTIFICATION.equals(report.getStatus())
                    && !HazardConstant.HAZARD_STATUS.RECTIFICATING.equals(report.getStatus())
                    && !HazardConstant.HAZARD_STATUS.BACK_AUDIT.equals(report.getStatus())){
                return new FebsResponse().fail().message("该隐患信息已经整改反馈过！");
            }
            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
            hazardReport.setUpdatedTime(new Date());
            hazardReport.setFeedbackDate(new Date());
            this.hazardReportService.submitHazardReportRectificationRecord(hazardReport,getCurrentUser());
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增整改反馈失败";
            log.error(message, e);
            throw new FebsException(message);
        }
    }


    /**
     * 整改反馈
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("转发整改反馈")
    @PostMapping("forwardToHazardReportRectification")
    @ResponseBody
    @RequiresPermissions("hazardReportRectification:feedback")
    public FebsResponse forwardToHazardReportRectification(@RequestBody  HazardReportDto hazardReport) throws FebsException {
        checkParams(hazardReport);
        try {
            HazardReport report = hazardReportService.findHazardReportById(hazardReport.getReportId());
            if(ObjectUtils.isEmpty(report)){
                return new FebsResponse().fail().message("待转发的隐患信息不存在!");
            }
            if(!HazardConstant.FORWARD_FLG.UN_FORWARD.equals(report.getForwardFlg())){
                return new FebsResponse().fail().message("该隐患信息已被转发，无法再次转发!");
            }
            hazardReport.setForwardFlg(HazardConstant.FORWARD_FLG.WAIT_AUDIT);
            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
            hazardReport.setUpdatedTime(new Date());
            this.hazardReportService.forwardToHazardReportRectificationRecord(hazardReport,getCurrentUser());
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增整改反馈失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 整改反馈
     * @author wanghw
     * @date 2024-08-20 09:23:04
     */
    @Log("保存整改反馈中")
    @PostMapping("saveHazardReportRectification")
    @ResponseBody
    @RequiresPermissions("hazardReportRectification:feedback")
    public FebsResponse saveHazardReportRectification(@RequestBody  HazardReportDto hazardReport) throws FebsException {
        checkParams(hazardReport);
        try {
            HazardReport queryReport = hazardReportService.findHazardReportById(hazardReport.getReportId());
            if(ObjectUtils.isEmpty(queryReport)){
                return new FebsResponse().fail().message("待整改的隐患信息不存在!");
            }
            if (!HazardConstant.HAZARD_STATUS.RECTIFICATION.equals(queryReport.getStatus()) &&
                    !HazardConstant.HAZARD_STATUS.RECTIFICATING.equals(queryReport.getStatus())){
                return new FebsResponse().fail().message("该隐患信息已经整改反馈过！");
            }

            if(HazardConstant.HAZARD_STATUS.BACK_RECTIFICATION.equals(hazardReport.getStatus())
                && HazardConstant.HAZARD_STATUS.BACK_AUDIT.equals(queryReport.getStatus())){
                return new FebsResponse().fail().message("审核退回的报告，无法进行再次退回");
            }
            hazardReport.setUpdatedBy(getCurrentUser().getUserName());
            hazardReport.setUpdatedTime(new Date());
            this.hazardReportService.saveHazardReportRectificationRecord(hazardReport,getCurrentUser());
            return new FebsResponse().success();
        } catch (Exception e) {
            String message = "新增整改反馈失败";
            log.error(message, e);
            return failure(e,message);
        }
    }

    /**
     * 校验参数
     * @param hazardReport
     */
    private void checkParams( HazardReportDto hazardReport) throws FebsException {
        if(StringUtils.isBlank(hazardReport.getReportId())){
            throw new FebsException("隐患ID不能为空");
        }
        if(StringUtils.isBlank(hazardReport.getStatus())){
            throw new FebsException("隐患状态不能为空");
        }
        if(HazardConstant.HAZARD_STATUS.WAITING_AUDIT.equals(hazardReport.getStatus())){
            //整改完成
            if(CollectionUtils.isEmpty(hazardReport.getFeedBackFileList())){
                throw new FebsException("整改反馈图片不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getFeedbackContent())){
                throw new FebsException("整改反馈备注不能为空");
            }

        }else if(HazardConstant.HAZARD_STATUS.BACK_RECTIFICATION.equals(hazardReport.getStatus())){
//            if(StringUtils.isBlank(hazardReport.getAuditRemark())){
//                throw new FebsException("整改反馈备注不能为空");
//            }

        }else if(HazardConstant.HAZARD_STATUS.PLAN.equals(hazardReport.getStatus())){
            if(StringUtils.isBlank(hazardReport.getForwardToUserName())){
                throw new FebsException("转发对象姓名不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getForwardToUserId())){
                throw new FebsException("转发对象UserId不能为空");
            }
            if(StringUtils.isBlank(hazardReport.getForwardToUserNo())){
                throw new FebsException("转发对象用户号不能为空");
            }

        }
    }
}
